package com.cpkso.buss.backend.trade.vo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.cpkso.buss.backend.trade.domain.TbOrder;
import com.cpkso.buss.backend.user.domain.User;

/**
 * @author wrzhxy@qq.com
 * @date 2018年5月12日
 */
@SuppressWarnings("serial")
public class StatisticsSpecification implements Specification<TbOrder> {
	// TODO 存储这个条件，用来初始化查询条件
	private StatisticsConditionVo sc;
	public StatisticsSpecification(StatisticsConditionVo sc) {
		this.sc = sc;
	}
	public StatisticsConditionVo getSc() {
		return sc;
	}
	public void setSc(StatisticsConditionVo sc) {
		this.sc = sc;
	}

	@Override
	public Predicate toPredicate(Root<TbOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		List<Predicate> list = new ArrayList<Predicate>();
		
//		StringUtils.isNoneBlank(sc.getUserId())
		// 按userid获取订单列表
        if (sc.getUserId() != null) {
        	// 不应该用数据库字段名，应该用属性名
        	Join<TbOrder, User> join = root.join("user", JoinType.LEFT);
        	list.add(cb.equal(join.get("id").as(Long.class), sc.getUserId()));
//            list.add(cb.equal(root.fetch("user.Id").getAttribute().as(Integer.class), sc.getUserId()));
        } else if (StringUtils.hasText(sc.getUsername())){
        	Join<TbOrder, User> join = root.join("user", JoinType.LEFT);
			list.add(cb.like(join.get("name").as(String.class), sc.getUsername()));
        }

        if (sc.getBeginDate() != null && sc.getEndDate() != null) {
        	// 买家号下单时间是否在某时段之间
        	list.add(cb.greaterThanOrEqualTo(root.get("buyerTime").as(Date.class), sc.getBeginDate()));
            list.add(cb.lessThanOrEqualTo(root.get("buyerTime").as(Date.class), sc.getEndDate()));
        }
        Predicate[] p = new Predicate[list.size()];
        return cb.and(list.toArray(p));
	}

}
